<?php
/*
	Used to prepare the 'package.xml' file.
	This script scans through a top level directory for all the files
	and generates the package.xml file.

	@author: Jean-Lou Dupont
	
	Aptana:  "${project_loc}/trunk/Tools/prepare.package.xml.php"  "${resource_loc}"
	
	- Execute the above Aptana/Eclipse 'external tools' command using PHP.
	- Select target resource e.g. /Zend directory
*/

if (!isset( $argv[1]))
{
	echo "Requires the target directory !\n";	
	die(0);
}
if (!is_dir( $argv[1]))
{
	echo "Must be a valid directory !\n";	
	die(0);
}
$cdir = $argv[1];

echo 'Source path: '.$cdir."\n";

$sdir = basename( $cdir );
echo 'Source directory name: '.$sdir."\n";

if ( 'zend' !== strtolower( $sdir ) )
{
	echo 'The source directory name should be called "Zend" !'."\n";
	die( 0 );
}
$tdir = dirname( $cdir );
echo 'Target directory for package.xml: '.$tdir."\n";

// get all the files
$all_files = getAllFiles( $cdir );

// trim off the base path
foreach( $all_files as &$file )
	$file = substr( $file, strlen( $cdir ) +1 );

#echo 'All files: '."\n";
#var_dump( $all_files );
#die( 1 );

// get the template
echo 'Reading template ... '."\n";
$tpl = @file_get_contents( dirname(__FILE__).'/package.xml.tpl' );
$msg = (false === $tpl ) ? 'failure!':'success';
echo $msg."\n";
if ( false === $tpl )
	die( 0 );

//  <file baseinstalldir="Zend" name="$file$" role="php" />
$contents = null;

foreach( $all_files as $file )
	$contents .= '<file baseinstalldir="Zend" name="'.$file.'" role="php" />'."\n";

$result = str_replace( '$all_files$', $contents, $tpl );

echo 'Writing package.xml file ... '."\n";
$bytes_written = @file_put_contents( $tdir.'/package.xml', $result ); 
if ( strlen( $result) === $bytes_written )
{
	echo 'success!'."\n";
	die (1);
}
	echo 'failure !!!'."\n";
	die (0);

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function getAllFiles( &$cdir )
{
	// Now read all the directories which effectively
	// constitutes the list of categories
	$all_files = @scandir( $cdir );
	
	// get rid of the . and .. entries
	$files = array();
	
	if (!empty( $all_files ))
		foreach( $all_files as &$file )
		{
			if ( ( '.' == $file ) || ( '..' == $file ))
				continue;
			if ( substr($file,0,1) === '.' )
				continue;
				
			// do we have another directory to scan?
			$path = $cdir."/".$file;
			$info = @filetype( $path );
			
			#echo ' path:'.$path."\n";
			
			if ( 'file' === $info )
			{
				$files[] = $cdir.'/'.$file;
				continue;
			}
			
			if ( 'dir' === $info )
			{
				$batch = getAllFiles( $path );
				if ( is_array( $batch ))
					$files = array_merge( $files, $batch );
			}
		}
	
	return $files;
}